package character;

import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.control.CharacterControl;
import com.jme3.math.Vector3f;
import com.jme3.scene.Spatial;
import action.Action;
import board.BoardUtil;
import player.Player;
import game.ResolutionController;
import game.ResolutionListener;
import misc.Vector3i;

public class TickingCharacterControl extends CharacterControl implements ResolutionListener {
    protected Character myCharacter;
    protected int ticksQueued;
    
    @Deprecated
    public TickingCharacterControl() {}
    
    public TickingCharacterControl(CollisionShape collisionShape, float stepHeight) {
        super(collisionShape, stepHeight);
        init();
    }
    
    private void init() {
        ResolutionController.registerResolutionListener(this);
    }

    @Override
    public void resolutionStarted() {
	myCharacter.getActionQueue().resetTicksQueued();
	resolutionUnpaused();
    }
    
    @Override
    public void tick() {
	Action currentAction = myCharacter.getActionQueue().getActions().peek();
	if(currentAction != null) {
	    currentAction.tickAction();
	}
    }
    
    @Override
    public void resolutionEnded() {
	resolutionPaused();
    }

    @Override
    public void resolutionUnpaused() {
        Action currentAction = myCharacter.getActionQueue().getActions().peek();
	if(currentAction != null) {
            if(currentAction.isStarted() && !currentAction.isCompleted())
                currentAction.unpause();
        }
    }

    @Override
    public void resolutionPaused() {
        Action currentAction = myCharacter.getActionQueue().getActions().peek();
	if(currentAction != null) {
            if(currentAction.isStarted() && !currentAction.isCompleted())
                currentAction.pause();
        }
    }
    
    public void setWalk(Vector3i destination, float speed) {
        Vector3f destWorld = BoardUtil.boardToWorld(destination).subtract(BoardUtil.boardToWorld(myCharacter.getBoardLocation()));
	setWalkDirection(destWorld.normalize().multLocal(speed));
    }
    public void stopWalking() {
        setWalkDirection(Vector3f.ZERO);
    }

    @Override
    public void setSpatial(Spatial spatial) {
        super.setSpatial(spatial);
        myCharacter = (Character)spatial;
    }
    
    @Override
    public Player getPlayer() {
        return myCharacter.getPlayer();
    }
}
